package com.eascs.web.o2o.report.quartz;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.app.runtime.RuntimeSetting;
import com.eascs.common.util.StringUtil;
import com.eascs.notify.constant.ModelResult;
import com.eascs.notify.mail.MailNotifyRequest;
import com.eascs.notify.mail.MailNotifyResponse;
import com.eascs.notify.mail.MailSendType;
import com.eascs.web.o2o.quartz.util.BaseJobUtil;
import com.eascs.web.o2o.quartz.util.ExecutorService;
import com.eascs.web.o2o.report.constants.FefundConstants;
import com.eascs.web.o2o.report.constants.SendType;
import com.eascs.web.o2o.report.dto.FtpConfig;
import com.eascs.web.o2o.report.dto.MessageDTO;
import com.eascs.web.o2o.report.dto.MessageReceiver;
import com.eascs.web.o2o.report.entity.WfEmail;
import com.eascs.web.o2o.report.entity.WfMessage;
import com.eascs.web.o2o.report.service.EmailService;
import com.eascs.web.o2o.report.service.MessageService;
import com.eascs.web.o2o.report.service.MsgService;
import com.eascs.web.o2o.report.util.FtpUtil;
import com.eascs.web.o2o.report.util.MailUtil;

@Component("MessageQuartz")
public class MessageQuartz  extends BaseJobUtil{
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Value("${msg.email.host}")
	private String host;	//smtp
	
	@Value("${msg.email.title}")
	private String title;	//邮件标题
	
	@Value("${msg.email.sender}")
	private String sender;	//发送者邮件
	
	@Value("${msg.email.sender.password}")
	private String password;	//发送者邮件密码
	@Value("${ftp.path}")
	private String	path;		// 路径
	
	@Value("${msg.message.sendername}")
	private String sendername;	//短信发送者
	@Inject
	MessageService messageService;
	@Inject
	MsgService msgService;
	@Inject
    EmailService emailService;
	
	@Inject
	MailUtil mailUtil;
	

	public void msgSend() {

		executor("MessageQuartz", "msgSend", "定时短信", new ExecutorService() {
			@Override
			public void exe() {
				//从DB读取未发的信息
				List<WfMessage> messageList=msgService.findWfMessage(0);
				SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd");
				if(!CollectionUtils.isEmpty(messageList)){
					for (WfMessage wfMessage : messageList) {
						MessageDTO	dto=new MessageDTO();
						List<MessageReceiver> receivers=new ArrayList<>();
						MessageReceiver receiver=new MessageReceiver();
						receiver.setName(wfMessage.getReceiveName());
						receiver.setPhone(wfMessage.getReceiveTelphone());
						receivers.add(receiver);
						dto.setMsgContent(wfMessage.getContent());
						dto.setReceivers(receivers);
						dto.setSenderName(sendername);
						if(wfMessage.getSendType().equals(SendType.NOW.getValue())){
							dto.setSendType(SendType.NOW);
						} else{
							dto.setSendType(SendType.ONTIME);
							if(null != wfMessage.getSendTime()){
								dto.setSendTime(s.format(wfMessage.getSendTime()));
								logger.error("定时短信没有时间");
							}
						}
						RuntimeSetting runtimeSetting = RuntimeSetting.get();
						boolean flag = false;
						if(runtimeSetting.getEnv().equals(FefundConstants.ENV_PROD)){
							 flag=messageService.sendMsg(dto);
						}
						if(flag){
							msgService.updateState(wfMessage.getMessageId());//成功之后修改短信状态
						} else{
							msgService.updateCounts(wfMessage.getMessageId());
							logger.info("发送短信失败：接收人[{}],接收人手机[{}],创建人[{}]", wfMessage.getReceiveName(), wfMessage.getReceiveTelphone(), sendername);
						}
						
					}
					
				} else{
					logger.info("没有短信需要发送");
				}
			}
		});
	}
	
	
	
	

	public void mailGenerSend() {
		executor("MessageQuartz", "mailGenerSend", "邮件发送", new ExecutorService() {
			@Override
			public void exe() {
				//从DB中读取所以未发送且发送次数小于三次的数据，发送完成后更新掉状态和发送时间
				List<WfEmail> emailList=emailService.findWfEmail(0);
				if(!CollectionUtils.isEmpty(emailList)){
					for (WfEmail wfEmail : emailList) {
						MailNotifyRequest mailNotifyRequest=new MailNotifyRequest();
						setParam(wfEmail, mailNotifyRequest);
						ModelResult<MailNotifyResponse> model=null;
						RuntimeSetting runtimeSetting = RuntimeSetting.get();
						if(runtimeSetting.getEnv().equals(FefundConstants.ENV_PROD)&&!(MailSendType.SCHEDULE).equals(wfEmail.getMailSendType())){
							try {
								 model=mailUtil.sendMail(mailNotifyRequest);
								 if(model.isSuccess()){
									 logger.info("邮件发送完成，插库信息为：[{}]", model.getModel().getResponseId());
									 emailService.updateState(wfEmail.getEmailId());
								 }else{
									 logger.error("邮件发送异常，异常code为：[{}],异常内容为：[{}]", model.getErrCode(),model.getErrMsg());
								 emailService.updateCounts(wfEmail.getEmailId());
								 }
							} catch (Exception e) {
							logger.error("邮件发送接口调用异常",e.getMessage());
							}
						}
					}
				} else{
				logger.info("没有邮件需要发送");
				}
			}
		});
	}

	private void setParam(WfEmail wfEmail, MailNotifyRequest mailNotifyRequest) {
		mailNotifyRequest.setTitle(wfEmail.getTitle());
		mailNotifyRequest.setContent(wfEmail.getContent());
		mailNotifyRequest.setSystemCode(wfEmail.getSystemCode());
		mailNotifyRequest.setMailSendType(MailSendType.SCHEDULE);
		mailNotifyRequest.setRecipientTo(wfEmail.getRecipients());
		mailNotifyRequest.setRequestId(wfEmail.getRequestId());
		mailNotifyRequest.setRequestDateTime(wfEmail.getRequestDateTime());
		mailNotifyRequest.setRecipientCc(wfEmail.getCc());
		mailNotifyRequest.setRecipientBcc(wfEmail.getRecipientBcc());
		mailNotifyRequest.setFrom(wfEmail.getSender());
		
		Set<String> fileSet=new HashSet<>();
		if(StringUtil.isNotBlank(wfEmail.getAppendix())){
			try {
				fileSet=FtpUtil.startDownload(FtpConfig.getInstance(), path, wfEmail.getAppendix());
			} catch (Exception e) {
				logger.info("发送邮件拉取FTP文件异常：[{}]", e.getMessage());
			}
		}
		if(!CollectionUtils.isEmpty(fileSet)){
			
			List<String> attach = new ArrayList<>();
			attach.add(path);
			mailNotifyRequest.setAttachmentPath(attach.toString().substring(1, attach.toString().length()-1));
		}
	}
	
	
	
	
}
